<!DOCTYPE html>
<html class="x-admin-sm">
<head>
    <meta charset="UTF-8">
    <title>宇成建筑</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="../statics/css/font.css">
    <link rel="stylesheet" href="../statics/plugins/layui/css/layui.css">
    <link rel="stylesheet" href="../statics/css/xadmin.css">
    <link rel="stylesheet" href="../statics/css/style.css">
    <style>
        .layui-colla-icon {
            left: 96% !important;
        }
    </style>
</head>

<body class='labelAuto'>
<div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="welcome.html">首页</a>
            <a href="javascript:;">仓库管理</a>
            <a href="javascript:;">仓库物资<span class="projectName"></span></a>
            <a>
                <cite>采购单</cite>
            </a>
        </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       onclick="location.reload()" title="刷新">
        <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i>
    </a>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right;margin-right:10px"
       onclick="window.history.go(-1)" title="后退">
        <i class="iconfontBlod" style="line-height:30px">&#xe74f;</i>
    </a>
</div>
<div class="layui-fluid">
    <div class="layui-d layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body search">
                    <form action="" class="layui-form livingList">
                        <div class="layui-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">收货状态</label>
                                <div class="layui-input-block">
                                    <select name="status" id="status">
                                        <option value="">-</option>
                                        <option value="0">未收货</option>
                                        <option value="1">收货中</option>
                                        <option value="2">已收货</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">供应商</label>
                                <div class="layui-input-block">
                                    <select name="supplierId" id="supplierId" lay_search>
                                        <option value="">-</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">搜索</label>
                                <div class="layui-input-block">
                                    <input type="search" autocomplete="off" class="layui-input" id="searchInput" placeholder="请输入订单号">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button class="layui-btn search" type="button" id='search'>
                                    <i class="iconfont layui-icon">&#xe615;</i>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="layui-card-body tableCardBody">
                    <table class="layui-table" id="lists" lay-filter="test"></table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script src="../statics/plugins/layui/layui.js" charset="utf-8"></script>
<script src='../statics/plugins/jQuery-3.2.1/jquery-3.2.1.min.js'></script>
<script type="text/javascript" src="../statics/plugins/X-admin/xadmin.js"></script>
<script type="text/javascript" src="../statics/js/public.js?v=1129"></script>
<script type="text/javascript">
    layui.use(['form', 'layer', "table","laydate"], function () {
        $('span.projectName').html(`(${localStorage.getItem('projectName')})`);
        var table = layui.table;
        var form = layui.form;
        var laydate = layui.laydate;
        $('#supplierId').empty().html(supplierSelect());
        form.render();
        var projectId = Number(getQueryString('projectId'));
        // 异步数据加载
        var lists = table.render({
            elem: '#lists', //绑定DOM元素
            id: 'lists', //table的id
            title: '人员列表',
            height: 'full-150',
            contentType: "application/json; charset=utf-8",
            url: url + '/finance/supplier/orderLists', //数据接口地址
            request: {
                pageName: 'page', //页码的参数名称，默认：page
                limitName: 'length' //每页数据量的参数名，默认：limit
            },
            method: 'POST',
            parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "data": res.data.data,
                    "msg": res.msg,
                    "count": res.data.count
                };
            },
            where: {
                projectId: projectId,
                search: "",
                token: getToken()
            },
            toolbar: '#toolbar',
            defaultToolbar: ['filter'],
            page: true, //开启分页
            limit: 10, //默认每页记录条数
            limits: [10, 20, 50], //每页记录条数可选数量
            cols: [
                [ //表头
                    {field: '', title: '编号', type: 'numbers', width: '8%'},
                    {field: 'ordersn', title: '单号',},
                    {field: 'supplierName', title: '供应商',},
                    {field: 'totalPrice', title: '货单总额'},
                    {
                        field: 'deliveryTime', title: '订单时间', templet: function (d) {
                            return d.deliveryTime.substr(0,10);
                        }
                    },
                    {
                        field: 'status', title: '收货状态', templet: function (d) {
                            switch (d.status) {
                                case 0:
                                    return '未收货';
                                case 1:
                                    return '收货中';
                                case 2:
                                    return '收货完成';
                                case 3:
                                    return '订单完成';
                            }
                        }
                    },
                    {field: 'adminName', title: '下单人'},
                    {
                        field: '', title: '操作', width: "27%", templet(d) {
                            var html=`<button class='layui-btn' lay-event="orderInfo">货单详情</button>`
                            if(d.status !== 0){
                                html+=`<button class='layui-btn' lay-event="log">收货记录</button>`;
                            }
                            if(d.status !== 3){
                                html+=`<button class='layui-btn' lay-event="complete">订单完成</button>`;
                            }
                            if(d.status === 0){
                                html+=`<button class='layui-btn' lay-event="editOrder">编辑货单</button>`;
                                html+=`<button class='layui-btn layui-btn-danger' lay-event="deleteOrder" auth="deleteOrder">删除货单</button>`;
                            }
                            return html;
                        }
                    }
                ]
            ],
            response: {
                statusName: 'code', //数据状态的字段名称，默认：code
                statusCode: 100000, //成功的状态码，默认：0
                msgName: 'msg', //状态信息的字段名称，默认：msg
                countName: 'count', //数据总数的字段名称，默认：count
                dataName: 'data' //数据列表的字段名称，默认：data
            },
            done: function () {
                permission();
            }
        });
        table.on('tool(test)', function (data) {
            if (data.event === 'orderInfo') {
                window.location.href = "warehouseSupplierOrderInfo.html?orderId="+data.data.id;
            }else if(data.event === 'editOrder'){
                let orderData = '';
                $.ajax({
                    url: url + "/finance/supplier/orderInfo2",
                    type: "POST",
                    data: {
                        orderId: data.data.id,
                        token: getToken()
                    },
                    async:false,
                    success: function (r) {
                        if (r.code == 100000) {
                            orderData = r.data;
                        } else {
                            tips('采购', r);
                        }
                    }
                });
                let orderInfoHtml = ''
                for(let i=0;i<orderData.orderInfo.length;i++){
                    orderInfoHtml+=`<div class='layui-inline'>
                               <label class='layui-form-label'>${i==0?'采购明细':''}</label>
                               <div class='layui-input-block' style="width:25%">
                                   <select name="materialId" lay-filter="materialId" lay-search value="">${materialSelect()}</select>
                               </div>
                               <div class='layui-input-block' style="width:15%">
                                   <select name="specId" lay-filter="specId" lay-search></select>
                               </div>
                               <div class='layui-input-block' style="width:8%">
                                   <input type="number" min="0" step="0.0001" class="layui-input" name="amount" placeholder="输入数量" value="${orderData.orderInfo[i].amount}">
                               </div>
                               <div class='layui-input-block' style="width:8%">
                                   <input type="text" class="layui-input" name="unitId" value=""  data-id="" disabled placeholder="计量单位">
                               </div>
                               <div class='layui-input-block' style="width:9%">
                                   <input type="number" min="0" step="0.01" class="layui-input" name="price" placeholder="输入单价" value="${orderData.orderInfo[i].price}">
                               </div>
                               <div class='layui-input-block' style="width:15%">
                                   <input type="text" class="layui-input" name="totalPrice" value="${orderData.orderInfo[i].totalPrice}">
                               </div>
                               <div class='layui-input-block' style="width:2%">
                                   <button type="button" class="layui-btn caigou btn btn-minus" style="width:26px">-</button>
                               </div>
                           </div>`
                }
                layer.open({
                    type: 1,
                    title: "采购",
                    area: ['70%', '90%'],
                    content: `
                    <form class='layui-form layerOpen' lay-filter="layerForm">
                        <div class='layui-item'>
                            <div class='layui-inline'>
                                <label class='layui-form-label'>采购时间</label>
                                <div class='layui-input-block' style="width:20%;">
                                    <input type="text" id="deliveryTime" class="layui-input" name="deliveryTime" value="">
                                </div>
                            </div>
                        </div>
                        <div class='layui-item supplier'>
                            <div class='layui-inline'>
                                <label class='layui-form-label'>供应商</label>
                                <div class='layui-input-block' style="width:25%">
                                    <select name="supplierId" lay-filter="supplierId" lay-search>${supplierSelect(true)}</select>
                                </div>
                            </div>
                        </div>
                        <div class='layui-item'>
                            <div class='layui-inline'>
                                <label class='layui-form-label'>支付方式</label>
                                <div class='layui-input-block' style="width:20%;">
                                    <select name="payType" lay-search>
                                        <option value="">-</option>
                                        <option value="1">现金</option>
                                        <option value="2">对公支付</option>
                                        <option value="3">后付款</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class='layui-item'>
                            <div class='layui-inline'>
                                <label class='layui-form-label'>单据总额</label>
                                <div class='layui-input-block'>
                                    <input type="number" min="0" class="layui-input" name="tPrice" value="${orderData.order.totalPrice}">
                                </div>
                            </div>
                        </div>
                        <div class='layui-item detail'>
                            ${orderInfoHtml}
                            <div class='layui-inline'>
                                <label class='layui-form-label'></label>
                                <div class='layui-input-block' style="width:25%">
                                    <select name="materialId" lay-filter="materialId" lay-search>${materialSelect()}</select>
                                </div>
                                <div class='layui-input-block' style="width:15%">
                                    <select name="specId" lay-filter="specId" lay-search></select>
                                </div>
                                <div class='layui-input-block' style="width:8%">
                                    <input type="number" min="0" step="0.0001" class="layui-input" name="amount" placeholder="输入数量">
                                </div>
                                <div class='layui-input-block' style="width:8%">
                                    <input type="text" class="layui-input" name="unitId" value=""  data-id="" disabled placeholder="计量单位">
                                </div>
                                <div class='layui-input-block' style="width:9%">
                                    <input type="number" min="0" step="0.01" class="layui-input" name="price" placeholder="输入单价">
                                </div>
                                <div class='layui-input-block' style="width:15%">
                                    <input type="text" class="layui-input" name="totalPrice" value="">
                                </div>
                                <div class='layui-input-block' style="width:2%">
                                    <button type="button" class="layui-btn caigou btn btn-plus" style="width:26px">+</button>
                                </div>
                            </div>
                        </div>
                        <div class='layui-item'>
                            <div class='layui-inline'>
                                <label class='layui-form-label'>备注</label>
                                <div class='layui-input-block'>
                                    <input type="text" class="layui-input" name="remark" value="${orderData.order.remark}">
                                </div>
                            </div>
                        </div>
                    </form>
                `,
                    btn: ['确认', '取消'],
                    skin: 'my-skin',
                    success: function () {
                        laydate.render({
                            elem: '#deliveryTime'
                            , type: 'date'
                            , max: 0
                            , value: orderData.order.deliveryTime.substr(0,10)
                        });
                        $('.layerOpen select[name=supplierId]').val(orderData.order.supplierId)
                        $('select[name=payType]').val(orderData.order.payType)
                        for(let i=0;i<orderData.orderInfo.length;i++){
                            let item = $('.detail div.layui-inline:eq('+i+')')
                            item.find('select[name=materialId]').val(orderData.orderInfo[i].materialId)
                            // 获取材料属性
                            let option = specSelect(orderData.orderInfo[i].materialId);
                            item.find('select[name=specId]').empty().html(option);

                            // 给属性下拉赋值
                            item.find('select[name=specId]').val(orderData.orderInfo[i].specId)
                            item.find('select[name=specId] option:selected');

                            var unitId = item.find('select[name=specId] option[value=' + orderData.orderInfo[i].specId + ']').data('unitid');
                            var unitName = item.find('select[name=specId] option[value=' + orderData.orderInfo[i].specId + ']').data('unitname');
                            item.find('input[name=unitId]').data('id', unitId).val(unitName)
                        }
                        form.render();
                    },
                    yes: function (index, layero) {
                        var supplierId = $('.layerOpen select[name=supplierId]').val();
                        var name = '';
                        var phone = '';
                        var address = '';
                        if (supplierId == 0) {
                            name = $('input[name=name]').val();
                            phone = $('input[name=phone]').val();
                            address = $('input[name=address]').val();
                            if (name == '' || address == '') {
                                tips('采购', {msg: '请完整填写供应商名称及地址'});
                            }
                        } else if (supplierId == '') {
                            tips('采购', {msg: '请选择材料供应商'});
                        }
                        var payType = $('select[name=payType]').val();
                        var tPrice = $('input[name=tPrice]').val();
                        var remark = $('input[name=remark]').val();
                        var deliveryTime = $('input[name=deliveryTime]').val();
                        if (deliveryTime == '') {
                            tips('采购', {msg: '请选择采购时间'});
                        }
                        var inline = $('.detail div.layui-inline');
                        var data = [];
                        for (var i = 0; i < inline.length; i++) {
                            materialId = Number($(inline[i]).find('select[name=materialId] option:selected').val());
                            specId = Number($(inline[i]).find('select[name=specId]').val());
                            amount = Number($(inline[i]).find('input[name=amount]').val());
                            unitId = Number($(inline[i]).find('select[name=specId] option:selected').data('unitid'));
                            price = Number($(inline[i]).find('input[name=price]').val());
                            totalPrice = Number($(inline[i]).find('input[name=totalPrice]').val());
                            if (materialId === '' || amount === '' || price === '' || unitId == 0 || totalPrice === '') {
                                tips('采购', {msg: '采购材料信息不完整'});
                                return false
                            }
                            if (materialId != 0 && amount != 0 && price!= 0){
                                data.push({
                                    materialId: materialId,
                                    specId: specId,
                                    amount: amount,
                                    unitId: unitId,
                                    price: price,
                                    totalPrice: totalPrice
                                })
                            }
                        }
                        $.ajax({
                            url: url + "/warehouse/warehouse/purchase",
                            type: "POST",
                            data: {
                                orderId:orderData.order.id,
                                projectId: projectId,
                                price: tPrice,
                                supplierId: Number(supplierId),
                                name: name,
                                phone: phone,
                                address: address,
                                payType: payType,
                                remark: remark,
                                deliveryTime: deliveryTime,
                                data: data,
                                token: getToken()
                            },
                            success: function (r) {
                                if (r.code == 100000) {
                                    tips('采购', r);
                                    setTimeout(function () {
                                        layer.closeAll();
                                        table.reload('lists');
                                    }, 2000)
                                } else {
                                    tips('采购', r);
                                }
                            }
                        })
                    }
                })
            }else if(data.event === 'deleteOrder'){
                layer.open({
                    type: 0,
                    title: "删除采购单",
                    area: ['40%', '30%'],
                    content: `是否删除此采购单，点击确认删除`,
                    btn: ['确认', '取消'],
                    skin: 'my-skin',
                    yes: function (index, layero) {
                        if (data.data.status != 0 ){
                            tips('采购单', {msg:"不能删除此采购单"});
                        }
                        $.ajax({
                            url: url + "/finance/supplier/deleteOrder",
                            type: "POST",
                            data: {
                                id: Number(data.data.id),
                                token: getToken()
                            },
                            success: function (r) {
                                if (r.code == 100000) {
                                    tips('删除采购单', r);
                                    setTimeout(function () {
                                        layer.closeAll();
                                        table.reload('lists');
                                    }, 2000)
                                } else {
                                    tips('删除采购单', r);
                                }
                            }
                        })
                    }
                })
            }else if(data.event === 'log'){
                window.location.href = "warehouseSupplierOrderReceived.html?orderId="+data.data.id;
            }else if(data.event === 'complete'){
                layer.open({
                    type: 0,
                    title: "采购完成",
                    area: ['40%', '30%'],
                    content: `请确认采购单是否已完成，点击确认完成采购`,
                    btn: ['确认', '取消'],
                    skin: 'my-skin',
                    yes: function (index, layero) {
                        $.ajax({
                            url: url + "/finance/supplier/complete",
                            type: "POST",
                            data: {
                                id: Number(data.data.id),
                                token: getToken()
                            },
                            success: function (r) {
                                if (r.code == 100000) {
                                    tips('采购完成', r);
                                    setTimeout(function () {
                                        layer.closeAll();
                                        table.reload('lists');
                                    }, 2000)
                                } else {
                                    tips('采购完成', r);
                                }
                            }
                        })
                    }
                })
            }
        });

        $('body').on('click', 'button.caigou.btn-plus', function () {
            var html = `<div class='layui-inline' style="margin-top:5px;">
                          <label class='layui-form-label'></label>
                          <div class='layui-input-block' style="width:25%">
                              <select name="materialId" lay-filter="materialId" lay-search>${materialSelect()}</select>
                          </div>
                          <div class='layui-input-block' style="width:15%">
                              <select name="specId" lay-filter="specId" lay-search></select>
                          </div>
                          <div class='layui-input-block' style="width:8%">
                              <input type="number" min="0" step="0.0001" class="layui-input" name="amount" placeholder="输入数量">
                          </div>
                          <div class='layui-input-block' style="width:8%">
                              <input type="text" class="layui-input" name="unitId" value=""  data-id="" disabled placeholder="计量单位">
                          </div>
                          <div class='layui-input-block' style="width:9%">
                              <input type="number" min="0" step="0.01" class="layui-input" name="price" placeholder="输入单价">
                          </div>
                          <div class='layui-input-block' style="width:15%">
                              <input type="text" class="layui-input" name="totalPrice" value="">
                          </div>
                          <div class='layui-input-block' style="width:2%">
                              <button type="button" class="layui-btn caigou btn btn-plus" style="width:26px">+</button>
                          </div>
                      </div>`
            $('.detail').append(html);
            $('.btn:not(:last)').removeClass('btn-plus').addClass('btn-minus').empty().html('-');
            form.render()
        })

        $('body').on('click', 'button.btn-minus', function () {
            $(this).parent().parent().remove();
            if ($(this).hasClass('chuku')) {
                label = '出库明细';
            } else {
                label = '入库明细';
            }
            var inline = $('.detail>div.layui-inline');
            $(inline[0]).css('margin-top', '0');
            $(inline[0]).find('label').empty().html(label);
        });

        form.on('select(materialId)', function (data) {
            var option = specSelect(data.value);
            $(data.elem).parent().parent().find('select[name=specId]').empty().html(option);
            form.render();
        });

        form.on('select(specId)', function (data) {
            var unitId = $(data.elem).find('option[value=' + data.value + ']').data('unitid');
            var unitName = $(data.elem).find('option[value=' + data.value + ']').data('unitname');
            $(data.elem).parent().parent().find('input[name=unitId]').data('id', unitId).val(unitName)
        });

        $('body').on('click', '#search', function () {
            var search = $('#searchInput').val();
            var supplierId = $('#supplierId').val();
            var status = $('#status').val();
            table.reload('lists', {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    projectId: projectId,
                    supplierId: supplierId,
                    status: status,
                    search: search,
                    token: getToken()
                }
            })
        })
    });
</script>
</html>